"""
工具管理路由
提供工具集和具体工具的查看和状态管理功能
"""

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from config.database import get_db_session
from pojo.ai_web_detail_tools import (
    AIWebDetailToolsResponse, AIWebDetailToolsListResponse,
    AIWebDetailToolsStatusUpdate, ToolParameter,
    AIWebDetailToolsInteractiveUpdate
)
from pojo.ai_web_detail_tools_model import AIWebDetailToolsModel
from pojo.ai_web_tools import (
    AIWebToolsResponse, AIWebToolsListResponse, AIWebToolsStatusUpdate,
    AIWebToolsDetailResponse, SingleToolModel
)
from pojo.ai_web_tools_model import AIWebToolsModel
from tools.ToolFactory import ToolFactory

router = APIRouter()


@router.get("/", response_model=AIWebToolsListResponse, summary="获取工具集列表")
async def get_tools_list(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        category_name: Optional[str] = Query(None, description="工具类名称模糊查询"),
        category_code: Optional[str] = Query(None, description="工具类代码查询"),
        is_enabled: Optional[int] = Query(None, description="状态筛选：1-可用，0-禁用"),
        db: Session = Depends(get_db_session)
):
    """获取工具集列表"""
    try:
        # 构建查询
        query = db.query(AIWebToolsModel)

        # 添加筛选条件
        if category_name:
            query = query.filter(AIWebToolsModel.category_name.like(f"%{category_name}%"))
        if category_code:
            query = query.filter(AIWebToolsModel.category_code.like(f"%{category_code}%"))
        if is_enabled is not None:
            query = query.filter(AIWebToolsModel.is_enabled == is_enabled)

        # 获取总数
        total = query.count()

        # 分页查询
        tools = query.offset((page - 1) * page_size).limit(page_size).all()

        # 转换为响应模型
        items = []
        for tool in tools:
            items.append(AIWebToolsResponse(
                id=tool.id,
                category_name=tool.category_name,
                category_code=tool.category_code,
                description=tool.description,
                is_enabled=tool.is_enabled,
                created_at=tool.created_at,
                updated_at=tool.updated_at
            ))

        return AIWebToolsListResponse(total=total, items=items)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具集列表失败: {str(e)}")


@router.get("/{tools_id}", response_model=AIWebToolsDetailResponse, summary="获取工具集详情")
async def get_tools_detail(tools_id: int, db: Session = Depends(get_db_session)):
    """获取工具集详情"""
    try:
        tool_model = db.query(AIWebToolsModel).filter(AIWebToolsModel.id == tools_id).first()
        if not tool_model:
            raise HTTPException(status_code=404, detail="工具集不存在")

        # 获取工具详情列表 - 只查询基础工具(tool_type=1)
        detail_tools = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == tools_id,
            AIWebDetailToolsModel.tool_type == 1
        ).all()

        tools = []
        for detail_tool in detail_tools:
            # 转换参数格式
            parameters = []
            for param in detail_tool.get_parameters():
                parameters.append(ToolParameter(
                    param_name=param.get('param_name', ''),
                    param_type=param.get('param_type', ''),
                    description=param.get('description', ''),
                    default_value=param.get('default_value'),
                    is_required=param.get('is_required', False)
                ))

            tools.append(SingleToolModel(
                id=detail_tool.id,
                tool_name=detail_tool.tool_name,
                description=detail_tool.description or '',
                is_enabled=detail_tool.is_enabled,
                parameters=parameters
            ))

        return AIWebToolsDetailResponse(
            id=tool_model.id,
            category_name=tool_model.category_name,
            category_code=tool_model.category_code,
            description=tool_model.description,
            is_enabled=tool_model.is_enabled,
            tools=tools,
            created_at=tool_model.created_at,
            updated_at=tool_model.updated_at
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具集详情失败: {str(e)}")


@router.patch("/{tools_id}/status", response_model=AIWebToolsResponse, summary="更新工具集状态")
async def update_tools_status(
        tools_id: int,
        status_data: AIWebToolsStatusUpdate,
        db: Session = Depends(get_db_session)
):
    """更新工具集状态"""
    try:
        tool_model = db.query(AIWebToolsModel).filter(AIWebToolsModel.id == tools_id).first()
        if not tool_model:
            raise HTTPException(status_code=404, detail="工具集不存在")

        tool_model.update_status(status_data.is_enabled)
        db.commit()
        db.refresh(tool_model)

        return AIWebToolsResponse(
            id=tool_model.id,
            category_name=tool_model.category_name,
            category_code=tool_model.category_code,
            description=tool_model.description,
            is_enabled=tool_model.is_enabled,
            created_at=tool_model.created_at,
            updated_at=tool_model.updated_at
        )

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具集状态失败: {str(e)}")


@router.get("/{tools_id}/tools", summary="获取工具集中的具体工具列表")
async def get_tools_in_category(tools_id: int, db: Session = Depends(get_db_session)):
    """获取工具集中的具体工具列表"""
    try:
        tool_model = db.query(AIWebToolsModel).filter(AIWebToolsModel.id == tools_id).first()
        if not tool_model:
            raise HTTPException(status_code=404, detail="工具集不存在")

        # 获取工具详情列表 - 只查询基础工具(tool_type=1)
        detail_tools = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == tools_id,
            AIWebDetailToolsModel.tool_type == 1
        ).all()

        tools = []
        for detail_tool in detail_tools:
            tools.append({
                "id": detail_tool.id,
                "tool_name": detail_tool.tool_name,
                "description": detail_tool.description,
                "is_enabled": detail_tool.is_enabled,
                "human_interactive_flag": detail_tool.human_interactive_flag,
                "parameters": detail_tool.get_parameters()
            })

        return {
            "category_id": tools_id,
            "category_name": tool_model.category_name,
            "category_code": tool_model.category_code,
            "tools": tools
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具列表失败: {str(e)}")


@router.patch("/{tools_id}/tools/{tool_name}/status", summary="更新具体工具状态")
async def update_tool_status(
        tools_id: int,
        tool_name: str,
        is_enabled: bool,
        db: Session = Depends(get_db_session)
):
    """更新工具集中具体工具的状态"""
    try:
        tool_model = db.query(AIWebToolsModel).filter(AIWebToolsModel.id == tools_id).first()
        if not tool_model:
            raise HTTPException(status_code=404, detail="工具集不存在")

        # 查找具体工具 - 只查询基础工具(tool_type=1)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == tools_id,
            AIWebDetailToolsModel.tool_name == tool_name,
            AIWebDetailToolsModel.tool_type == 1
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具不存在")

        # 更新状态
        detail_tool.update_status(is_enabled)
        db.commit()

        return {
            "message": f"工具 '{tool_name}' 状态更新成功",
            "tool_name": tool_name,
            "is_enabled": is_enabled
        }

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具状态失败: {str(e)}")


@router.get("/factory/available", summary="获取可用的工具类型")
async def get_available_tool_types():
    """获取ToolFactory中可用的工具类型"""
    try:
        available_types = ToolFactory.get_available_types()
        return {
            "available_types": available_types,
            "count": len(available_types)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取可用工具类型失败: {str(e)}")


@router.post("/factory/initialize", summary="初始化所有工具到数据库")
async def initialize_all_tools(db: Session = Depends(get_db_session)):
    """初始化ToolFactory中的所有工具到数据库"""
    try:
        results = ToolFactory.initialize_all_tools(db)

        success_count = sum(1 for success in results.values() if success)
        total_count = len(results)

        return {
            "message": f"工具初始化完成，成功 {success_count}/{total_count} 个工具",
            "results": results,
            "success_count": success_count,
            "total_count": total_count
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"工具初始化失败: {str(e)}")


@router.get("/enabled/list", summary="获取启用的工具列表")
async def get_enabled_tools(db: Session = Depends(get_db_session)):
    """获取启用的工具列表"""
    try:
        enabled_tools = ToolFactory.get_enabled_tools(db)
        return {
            "enabled_tools": enabled_tools,
            "count": len(enabled_tools)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取启用工具列表失败: {str(e)}")


# 新增：工具详情管理接口

@router.get("/detail/", response_model=AIWebDetailToolsListResponse, summary="获取工具详情列表")
async def get_detail_tools_list(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        parent_id: Optional[int] = Query(None, description="工具集ID筛选"),
        tool_type: Optional[int] = Query(None, description="工具类型筛选（1=基础工具,2=MCP工具）"),
        tool_name: Optional[str] = Query(None, description="工具名称模糊查询"),
        is_enabled: Optional[bool] = Query(None, description="状态筛选"),
        db: Session = Depends(get_db_session)
):
    """获取工具详情列表"""
    try:
        # 构建查询
        query = db.query(AIWebDetailToolsModel)

        # 添加筛选条件
        if parent_id:
            query = query.filter(AIWebDetailToolsModel.parent_id == parent_id)
        if tool_type:
            query = query.filter(AIWebDetailToolsModel.tool_type == tool_type)
        if tool_name:
            query = query.filter(AIWebDetailToolsModel.tool_name.like(f"%{tool_name}%"))
        if is_enabled is not None:
            query = query.filter(AIWebDetailToolsModel.is_enabled == is_enabled)

        # 获取总数
        total = query.count()

        # 分页查询
        tools = query.offset((page - 1) * page_size).limit(page_size).all()

        # 转换为响应模型
        items = []
        for tool in tools:
            items.append(AIWebDetailToolsResponse(
                id=tool.id,
                parent_id=tool.parent_id,
                tool_name=tool.tool_name,
                description=tool.description,
                is_enabled=tool.is_enabled,
                parameters=tool.get_parameters(),
                created_at=tool.created_at,
                updated_at=tool.updated_at
            ))

        return AIWebDetailToolsListResponse(total=total, items=items)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具详情列表失败: {str(e)}")


@router.get("/detail/{tool_id}", response_model=AIWebDetailToolsResponse, summary="获取工具详情")
async def get_detail_tool(tool_id: int, db: Session = Depends(get_db_session)):
    """获取工具详情"""
    try:
        tool = db.query(AIWebDetailToolsModel).filter(AIWebDetailToolsModel.id == tool_id).first()
        if not tool:
            raise HTTPException(status_code=404, detail="工具不存在")

        return AIWebDetailToolsResponse(
            id=tool.id,
            parent_id=tool.parent_id,
            tool_name=tool.tool_name,
            description=tool.description,
            is_enabled=tool.is_enabled,
            parameters=tool.get_parameters(),
            created_at=tool.created_at,
            updated_at=tool.updated_at
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具详情失败: {str(e)}")


@router.patch("/detail/{tool_id}/status", response_model=AIWebDetailToolsResponse, summary="更新工具详情状态")
async def update_detail_tool_status(
        tool_id: int,
        status_data: AIWebDetailToolsStatusUpdate,
        db: Session = Depends(get_db_session)
):
    """更新工具详情状态"""
    try:
        tool = db.query(AIWebDetailToolsModel).filter(AIWebDetailToolsModel.id == tool_id).first()
        if not tool:
            raise HTTPException(status_code=404, detail="工具不存在")

        tool.update_status(status_data.is_enabled)
        db.commit()
        db.refresh(tool)

        return AIWebDetailToolsResponse(
            id=tool.id,
            parent_id=tool.parent_id,
            tool_name=tool.tool_name,
            description=tool.description,
            is_enabled=tool.is_enabled,
            parameters=tool.get_parameters(),
            created_at=tool.created_at,
            updated_at=tool.updated_at
        )

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具状态失败: {str(e)}")


@router.patch("/detail/{tool_id}/interactive", response_model=AIWebDetailToolsResponse,
              summary="更新工具详情人工交互标识")
async def update_detail_tool_interactive(
        tool_id: int,
        interactive_data: AIWebDetailToolsInteractiveUpdate,
        db: Session = Depends(get_db_session)
):
    """更新工具详情人工交互标识"""
    try:
        tool = db.query(AIWebDetailToolsModel).filter(AIWebDetailToolsModel.id == tool_id).first()
        if not tool:
            raise HTTPException(status_code=404, detail="工具不存在")

        tool.update_human_interactive_flag(interactive_data.human_interactive_flag)
        db.commit()
        db.refresh(tool)

        return AIWebDetailToolsResponse(**tool.to_dict())

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具人工交互标识失败: {str(e)}")


@router.patch("/{tools_id}/tools/{tool_name}/interactive", summary="更新具体工具人工交互标识")
async def update_tool_interactive(
        tools_id: int,
        tool_name: str,
        human_interactive_flag: int,
        db: Session = Depends(get_db_session)
):
    """更新工具集中具体工具的人工交互标识"""
    try:
        tool_model = db.query(AIWebToolsModel).filter(AIWebToolsModel.id == tools_id).first()
        if not tool_model:
            raise HTTPException(status_code=404, detail="工具集不存在")

        # 查找具体工具 - 只查询基础工具(tool_type=1)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == tools_id,
            AIWebDetailToolsModel.tool_name == tool_name,
            AIWebDetailToolsModel.tool_type == 1
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具不存在")

        # 更新人工交互标识
        detail_tool.update_human_interactive_flag(human_interactive_flag)
        db.commit()

        return {
            "message": f"工具 '{tool_name}' 人工交互标识更新成功",
            "tool_name": tool_name,
            "human_interactive_flag": human_interactive_flag
        }

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具人工交互标识失败: {str(e)}")
